package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.SystemColor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;

import model.DatePicker;
import model.DeviceTableModel;
import model.FormatFactory;
import model.NumberCellEditor;
import model.NumberRenderer;
import model.StoreImages;
import model.UICommand;

import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.JXSearchField;
import org.jdesktop.swingx.JXSearchField.LayoutStyle;
import org.jdesktop.swingx.JXTable;

import com.alee.laf.WebLookAndFeel;
import com.alee.laf.toolbar.WebToolBar;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

import controller.DeviceController;

public class DevicePanel extends JPanel {
	private static final long serialVersionUID = 638230385226310121L;
	public static final String getDevice = null;
	private JTextField txt_id;
	private JTextField txt_provider;
	private JTextField txt_name;
	private JTextField txt_amount;
	private JTextField txt_type;
	private JXDatePicker txt_date;
	private JXCollapsiblePane advanced;
	private JXTable table;
	private JXSearchField searchField;
	private JCheckBox chck_id;
	private JCheckBox chck_amount;
	private JCheckBox chck_provider;
	private JCheckBox chck_type;
	private JCheckBox chck_name;
	private JCheckBox chck_date;
	private ArrayList<JTextField> group;
	private WebToolBar toolBar;

	public DevicePanel(DeviceTableModel tableModel, DeviceController control) {
		this.group = new ArrayList<JTextField>();
		setLayout(new BorderLayout(0, 0));

		JPanel panel_2 = new JPanel();
		add(panel_2, BorderLayout.NORTH);
		panel_2.setLayout(new BorderLayout(0, 0));

		JPanel panel = new JPanel();
		panel_2.add(panel, BorderLayout.NORTH);
		panel.setBorder(new TitledBorder(UIManager
				.getBorder("TitledBorder.border"),
				"Th\u00F4ng tin t\u00ECm ki\u1EBFm", TitledBorder.LEADING,
				TitledBorder.TOP, null, new Color(51, 153, 255)));
		panel.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, },
				new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, }));

		JLabel btnNewButton = new JLabel("Tìm kiếm");
		panel.add(btnNewButton, "1, 1, right, default");

		JLabel lblNewLabel = new JLabel("");
		lblNewLabel.setToolTipText("Tìm kiếm nâng cao");
		lblNewLabel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				advanced.setCollapsed(!advanced.isCollapsed());
			}
		});

		searchField = new JXSearchField();
		searchField.setActionCommand("schFid");
		searchField.addActionListener(control);
		searchField.setLayoutStyle(LayoutStyle.MAC);
		searchField.setPrompt("Tối ưu tìm kiếm bằng cách thiết lập nâng cao");
		searchField.setToolTipText("Tìm kiếm mặc định theo mã sản phẩm");
		searchField.setColumns(27);
		panel.add(searchField, "3, 1, fill, default");
		lblNewLabel.setIcon(StoreImages.getIcon(StoreImages.ADVANCED_ICON));
		panel.add(lblNewLabel, "5, 1");

		JButton btnNewButton_2 = new JButton("");
		btnNewButton_2.setFocusable(false);
		btnNewButton_2.setActionCommand("search");
		btnNewButton_2.addActionListener(control);
		btnNewButton_2.setIcon(StoreImages.getIcon(StoreImages.SEARCH_ICON));
		panel.add(btnNewButton_2, "7, 1");

		advanced = new JXCollapsiblePane();
		advanced.setCollapsed(true);
		advanced.setBorder(new TitledBorder(null,
				"T\u00ECm ki\u1EBFm n\u00E2ng cao", TitledBorder.LEADING,
				TitledBorder.TOP, null, SystemColor.textHighlight));
		panel_2.add(advanced, BorderLayout.CENTER);
		Container advanConttainer = advanced.getContentPane();
		advanConttainer.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"), }, new RowSpec[] {
				FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, }));

		// TODO check box
		chck_id = new JCheckBox("Mã sản phẩm");
		chck_id.setActionCommand("id");
		chck_id.addActionListener(control);
		advanConttainer.add(chck_id, "1, 1");
		advanConttainer.setVisible(false);
		txt_id = new JTextField();
		txt_id.setEditable(false);
		advanConttainer.add(txt_id, "3, 1");
		txt_id.setColumns(10);

		chck_amount = new JCheckBox("Số lượng tồn kho");
		chck_amount.setActionCommand("amount");
		chck_amount.addActionListener(control);
		advanConttainer.add(chck_amount, "5, 1");

		txt_amount = new JTextField();
		txt_amount.setEditable(false);
		advanConttainer.add(txt_amount, "7, 1");
		txt_amount.setColumns(10);

		chck_provider = new JCheckBox("Nhà sản xuất");
		chck_provider.setActionCommand("provider");
		chck_provider.addActionListener(control);
		advanConttainer.add(chck_provider, "1, 3");

		txt_provider = new JTextField();
		txt_provider.setEditable(false);
		advanConttainer.add(txt_provider, "3, 3");
		txt_provider.setColumns(10);

		chck_type = new JCheckBox("Loại sản phẩm");
		chck_type.setActionCommand("type");
		chck_type.addActionListener(control);
		advanConttainer.add(chck_type, "5, 3");

		txt_type = new JTextField();
		txt_type.setEditable(false);
		advanConttainer.add(txt_type, "7, 3");
		txt_type.setColumns(10);

		chck_name = new JCheckBox("Tên sản phẩm");
		chck_name.setActionCommand("name");
		chck_name.addActionListener(control);
		advanConttainer.add(chck_name, "1, 5");

		txt_name = new JTextField();
		txt_name.setEditable(false);
		advanConttainer.add(txt_name, "3, 5");
		txt_name.setColumns(10);

		chck_date = new JCheckBox("Ngày nhập");
		chck_date.setActionCommand("date");
		chck_date.addActionListener(control);
		advanConttainer.add(chck_date, "5, 5");

		txt_date = DatePicker.createDatePicker(18, DatePicker.DEFAULT_ICON);
		txt_date.setFormats(new SimpleDateFormat("yyyy/MM/dd"));
		txt_date.setEditable(false);
		advanConttainer.add(txt_date, "7, 5");

		JPanel panel_1 = new JPanel();
		add(panel_1, BorderLayout.CENTER);
		panel_1.setBorder(new TitledBorder(null, "Danh sách hàng trong kho",
				TitledBorder.LEADING, TitledBorder.TOP, null,
				SystemColor.textHighlight));
		panel_1.setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane = new JScrollPane();
		panel_1.add(scrollPane, BorderLayout.CENTER);
		scrollPane
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrollPane
				.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

		// TODO create table
		table = new JXTable(tableModel);
		table.setHorizontalScrollEnabled(true);
		scrollPane.setViewportView(table);

		table.getColumnModel().getColumn(0)
				.setCellRenderer(new NumberRenderer());
		table.getTableHeader().setToolTipText("Test Tool Tip");
		table.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {

					@Override
					public void valueChanged(ListSelectionEvent e) {

					}
				});

		FormatFactory.formatHeader(table, SwingConstants.CENTER);
		FormatFactory.formatHighlighter(table, null);
		table.packAll();

		// TODO device editor
		table.setDefaultEditor(Double.class, new NumberCellEditor(
				new Double(0), null));
		table.setDefaultEditor(Integer.class, new NumberCellEditor(new Integer(
				0), null));
		table.setDefaultRenderer(Date.class, new DefaultTableCellRenderer());

		// TODO tool bar
		toolBar = new WebToolBar();
		FormatFactory.formatToolBar(toolBar);
		panel_1.add(toolBar, BorderLayout.EAST);

		toolBar.add(FormatFactory.createButtonToolBar("Tải lại dữ liệu",
				UICommand.RELOAD_CMD,
				StoreImages.getIcon(StoreImages.REFRESH_ICON), control));

		toolBar.add(FormatFactory.createButtonToolBar("Lưu",
				UICommand.SAVE_CMD, StoreImages.getIcon(StoreImages.SAVE_ICON),
				control));

		// TODO set name
		txt_id.setName("id");
		txt_name.setName("name");
		txt_provider.setName("provider");
		txt_amount.setName("amount");
		txt_type.setName("type");
		txt_date.getEditor().setName("inputday");

		// TODO group
		group.add(txt_id);
		group.add(txt_name);
		group.add(txt_provider);
		group.add(txt_amount);
		group.add(txt_type);
		group.add(txt_date.getEditor());
	}

	// TODO
	public void stopCellEditing() {
		TableCellEditor cellEditor = table.getCellEditor();
		if (cellEditor != null)
			cellEditor.stopCellEditing();
	}

	public void setTextID() {
		this.txt_id.setText(this.searchField.getText());
	}

	public void setEditable(String name) {
		switch (name) {
		case "id":
			txt_id.setEditable(chck_id.isSelected());
			break;
		case "amount":
			txt_amount.setEditable(chck_amount.isSelected());
			break;
		case "provider":
			txt_provider.setEditable(chck_provider.isSelected());
			break;
		case "type":
			txt_type.setEditable(chck_type.isSelected());
			break;
		case "name":
			txt_name.setEditable(chck_name.isSelected());
			break;
		case "date":
			txt_date.setEditable(chck_date.isSelected());
			break;
		}
	}

	public int getSetlectedRow() {
		return table.getSelectedRow();
	}

	public String getSearchText() {
		return searchField.getText();
	}

	public String getDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		return sdf.format(txt_date.getDate());
	}

	public boolean isSelectedGroup() {
		for (int i = 0; i < group.size(); i++) {
			if (group.get(i).isEditable() && !group.get(i).getText().equals(""))
				return true;
		}
		return false;
	}

	public ArrayList<Object[]> getQuery() {
		ArrayList<Object[]> result = new ArrayList<Object[]>();

		for (int i = 0; i < group.size(); i++) {
			if (group.get(i).isEditable() && !group.get(i).getText().equals("")) {
				String[] tmp = new String[3];
				String name = group.get(i).getName();

				tmp[0] = name;
				if (name.equals("amount") || name.equals("inputday")) {
					tmp[1] = " = ";
					tmp[2] = "'".concat(group.get(i).getText()).concat("'");
				} else {
					tmp[1] = " LIKE ";
					tmp[2] = "'%".concat(group.get(i).getText()).concat("%'");
				}
				result.add(tmp);
			}
		}
		return result;
	}

	public static void main(String[] args) {
		WebLookAndFeel.install();
		JFrame frame = new JFrame();
		DeviceTableModel tableModel = new DeviceTableModel();
		DeviceController control = new DeviceController(tableModel);
		frame.getContentPane().add(control.getView());
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
	}

}
